package com.zzyl.intercept;

import cn.hutool.core.util.StrUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 移动端拦截器
 */
@Slf4j
@Component
public class MobileInterceptor implements HandlerInterceptor {


    @Autowired
    JwtTokenProperties jwtTokenProperties;

    /**
     * 在handler之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 从请求头中获取jwt
        String jwt = request.getHeader("Authorization");

        if (StrUtil.isBlank(jwt)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //2. 解析jwt，获取用户id
        try {
            Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), jwt);
            String id = claims.get("id").toString();

            //将用户id存放到本地线程
            ThreadLocalUtil.set(Long.valueOf(id));
        } catch (Exception e) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //3. 放行
        return true;
    }
}